package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entitry.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@Transactional
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    CategoryService categoryService;


    //添加菜品
    @PostMapping
    public R<Category> insertCategory(HttpServletRequest request, @RequestBody Category category) {

//        category.setCreateUser((Long)(request.getSession().getAttribute("employee")));
//        category.setUpdateUser((Long)(request.getSession().getAttribute("employee")));
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());

        //调用添加方法
        boolean save = categoryService.save(category);

        //如果成功，返回success
        if (save) {
            return R.success(category);
        }

        //失败，返回error
        return R.error("添加失败！");
    }


    //分页查询
    @GetMapping("/page")
    public R<Page<Category>> selectPage(int page, int pageSize) {

        //调用分页办法
        Page<Category> pageResult = new Page<>(page, pageSize);
        categoryService.page(pageResult);
        return R.success(pageResult);
    }

    //删除分类
    @DeleteMapping
    public R deleteCategory(Long id) {


        boolean removeById = categoryService.delete(id);
        if (removeById) {
            return R.success("删除成功！");
        }
        return R.error("删除失败！");
    }


    //修改分类
    @PutMapping
    public R update(@RequestBody Category category) {
        boolean result = categoryService.updateById(category);
        if (result) {
            return R.success("修改成功！");
        }
        return R.error("修改失败！");
    }


    @GetMapping("/list")
    public R<List<Category>> getGategoryType(Integer type) {

        //使用条件构建器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.eq(type != null,Category::getType, type).orderByDesc(Category::getSort);


        List<Category> list = categoryService.list(lqw);
        return R.success(list);
    }


}
